package com.ruoyi.web.controller.fx;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.config.WxV3PayConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.CodeGeneratorUtil;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.fx.FxStore;
import com.ruoyi.system.domain.fx.FxSupplierGood;
import com.ruoyi.system.service.fx.IFxStoreService;
import com.ruoyi.web.controller.common.WeChatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import static com.ruoyi.common.constant.Constants.FX_COM;
import static com.ruoyi.common.constant.Constants.HTTPS;
import static com.ruoyi.common.utils.CodeGeneratorUtil.createQrCode;

/**
 * 门店Controller
 *
 * @author ruoyi
 * @date 2024-07-23
 */
@RestController
@RequestMapping("/fx/store")
public class FxStoreController extends BaseController {
    @Autowired
    private IFxStoreService fxStoreService;

    /**
     * 查询门店列表
     */
    @GetMapping("/list")
    public TableDataInfo list(FxStore fxStore) {
        startPage();
        List<FxStore> list = fxStoreService.selectFxStoreList(fxStore);
        return getDataTable(list);
    }

    @GetMapping("/getStoreWxCode")
    public AjaxResult getWxCode(String storeId){
        String s = new WeChatUtils().downloadMiniCode(WxV3PayConfig.APP_ID, WxV3PayConfig.secret, "", "", "");
        return AjaxResult.success(s);
    }

    /**
     * 查询门店列表（app）
     *
     * @param fxStore
     * @return
     */
    @GetMapping("/listApp")
    public AjaxResult listApp(FxStore fxStore) {
        String cityString = fxStore.getCityString();
//        if (StringUtils.isEmpty(cityString))
//            return error("城市名称不能为空");
//        String longitude = fxStore.getLongitude();
//        String latitude = fxStore.getLatitude();
//        if (StringUtils.isEmpty(longitude))
//            throw new GlobalException("经度不能为空");
//        if (StringUtils.isEmpty(latitude))
//            throw new GlobalException("维度名称不能为空");
        fxStore.setIsInitiate(0L);
        Collection<FxStore> zyStores = fxStoreService.selectFxStoreListApp(fxStore);
        if (CollectionUtils.isEmpty(zyStores)) {
            return AjaxResult.success(new ArrayList<>());
        }
        return success(zyStores);
    }

    /**
     * 导出门店列表
     */
    @Log(title = "门店", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, FxStore fxStore) {
        List<FxStore> list = fxStoreService.selectFxStoreList(fxStore);
        ExcelUtil<FxStore> util = new ExcelUtil<FxStore>(FxStore.class);
        util.exportExcel(response, list, "门店数据");
    }

    /**
     * 获取门店详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(fxStoreService.selectFxStoreById(id));
    }

    /**
     * 首页搜索框
     *
     * @return
     */
    @GetMapping("/portalSearch")
    public AjaxResult portalSearch(String cityString,String search, String longitude, String latitude) {
        return success(fxStoreService.portalSearch(cityString, search, longitude, latitude));
    }

    /**
     * 新增门店
     */
    @Log(title = "门店", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody FxStore fxStore) {
        fxStore.setCreateBy(getUsername());
        fxStore.setCreateTime(DateUtils.getNowDate());
        return toAjax(fxStoreService.insertFxStore(fxStore));
    }

    /**
     * 修改门店
     */
    @Log(title = "门店", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody FxStore fxStore) {
        fxStore.setUpdateTime(DateUtils.getNowDate());
        return toAjax(fxStoreService.updateFxStore(fxStore));
    }

    /**
     * 禁用门店
     * @param fxStore 参数
     * @return
     */
    @GetMapping("/forbiddenStore")
    public AjaxResult forbidden(FxStore fxStore) {
        fxStore.setUpdateTime(DateUtils.getNowDate());
        return toAjax(fxStoreService.forbidden(fxStore));
    }


    /**
     * 删除门店
     */
    @Log(title = "门店", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(fxStoreService.updateFxStoreByIds(ids));
    }

    /**
     * 创建店铺分销码维码（生成二维码）
     *
     * @param ids
     * @return
     */
    @GetMapping("/createQrCodes")
    public AjaxResult createQrCodes(Long[] ids) {
        // 获取当前日期
        LocalDate currentDate = LocalDate.now();
        // 定义日期格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
        // 将日期格式化为指定格式的字符串
        String formattedDate = currentDate.format(formatter);
        // 上传文件路径
        String filePath = RuoYiConfig.getUploadPath() + "/storeBarCode/" + formattedDate;
        String qrCodeImgPath = null;
        for (Long id : ids) {
            String url = HTTPS + FX_COM + "/dist?storeId="+id;
            // 上传文件路径
            qrCodeImgPath = createQrCode(url, filePath);

            System.out.println("---------------- :"+qrCodeImgPath);
            String imgUrl = "/profile/upload/storeBarCode/" + formattedDate + qrCodeImgPath;
            FxStore fxStore = new FxStore();
            fxStore.setId(id);
            fxStore.setStoreQrCodeUrl(imgUrl);
            fxStoreService.updateFxStore(fxStore);
        }
        return AjaxResult.success("创建成功");
    }
}
